package lucky.xiong.basic.反射;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class 动态设置值 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
        AA a = new AA("脏三",18, Arrays.asList("吃饭","睡觉"),true);
        System.out.println(a);
        Map<String,Object> values = new HashMap<>();
        values.put("name","zzz");
        values.put("age",66);
        values.put("hobbies",Arrays.asList("hhh","cccc"));
        values.put("alive",false);
        Class<? extends AA> aClass = a.getClass();
        values.forEach((k,v)->{
            System.out.println(k+":"+v);
            for (Field field : aClass.getDeclaredFields()) {
                System.out.println(field.getName()+":"+field.getType());
                if (field.getName().equals(k)&&field.getType().equals(v.getClass())){
                    try {
                        field.setAccessible(true);
                        field.set(a,v);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        });
        // 直接获取指定名称的值
//        Field field = aClass.getDeclaredField("name");
//        // 如果是Private 变量，需要设置
//        field.setAccessible(true);
//        field.set(a,values.get("name"));

        System.out.println(a);
    }
}
